<?php
define("PATH_CFG", __DIR__ . '/config/');
define("PATH_APP", __DIR__ . '/app/');
define("PATH_MODEL", __DIR__ . '/model/');
define("PATH_LIB", __DIR__ . '/lib/');
define("PATH_SERVICE", __DIR__ . '/service/');
define("PATH_UTILS", __DIR__ . '/utils/');
define("PATH_DATA", __DIR__ . '/data/');

set_exception_handler(function ($exception) {
	$content = <<<TEXT
错误码：{$exception->getCode()}
错误信息：{$exception->getMessage()}
调试trace：{$exception->getTraceAsString()}
TEXT;
	$path = PATH_DATA . 'logs/';
	if (!is_dir($path)) {
		mkdir($path, '755', true);
	}
	$fileName = $path . 'errLogs.log';
	$content = '[' . date('Y-m-d H:i:s') . '][ERROR] ##' . $content . PHP_EOL;
	return file_put_contents($fileName, $content, FILE_APPEND);
});


//set error handler
set_error_handler(function ($errno, $errStr, $errFile, $errLine) {
	if (!(error_reporting() & $errno)) {
		//错误码未包含在错误报告中
		return true;
	}
	$str = '';
	switch ($errno) {
		case E_ERROR:
		case E_CORE_ERROR:
		case E_USER_ERROR:
		case E_COMPILE_ERROR:
			$str .= "[ERROR]:##[$errno] $errStr\n";
			$str .= "  错误位置在 $errFile 文件，第 $errLine 行";
			$str .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
			$str .= "Aborting...\n";
			break;
			
		case E_WARNING:
		case E_CORE_WARNING:
		case E_USER_WARNING:
		case E_COMPILE_WARNING:
			$str .= "[WARNING]:##[$errno] $errStr\n";
			$str .= "  错误位置在 $errFile 文件，第 $errLine 行";
			break;

		case E_NOTICE:
		case E_USER_NOTICE:
			$str .= "[NOTICE]:##[$errno] $errStr\n";
			$str .= "  错误位置在 $errFile 文件，第 $errLine 行";
			break;

		default:
			$str .= "[Unknown error type]:## [$errno] $errStr\n";
			$str .= "  错误位置在 $errFile 文件，第 $errLine 行";
			break;
	}

	$content = '[' . date('Y-m-d H:i:s') . '] ' . $str . PHP_EOL;
	$fileName = PATH_DATA . 'logs/errLogs.log';
	file_put_contents($fileName, $content, FILE_APPEND);
	return true;
});

register_shutdown_function(function () {
	$error = error_get_last();
	switch ($error['type'] ?? null) {
		case E_ERROR :
		case E_PARSE :
		case E_CORE_ERROR :
		case E_COMPILE_ERROR :
			$message = $error['message'] . PHP_EOL;
			if (isset($_SERVER['REQUEST_URI'])) {
				$message .= '[QUERY] ' . $_SERVER['REQUEST_URI'];
			}
			$content = '[' . date('Y-m-d H:i:s') . '] ##['.$error['type'].']' . $message . PHP_EOL;
			$fileName = PATH_DATA . 'logs/errLogs.log';
			file_put_contents($fileName, $content, FILE_APPEND);
			break;
	}
});
